package com.example.ivos.application.service.impl;

import com.example.ivos.application.mapper.ApplicationMapper;
import com.example.ivos.application.pojo.dto.ApplicationQuery;
import com.example.ivos.application.pojo.dto.ApplicationSaveParam;
import com.example.ivos.application.pojo.entity.Application;
import com.example.ivos.application.pojo.vo.ApplicationVO;
import com.example.ivos.application.service.ApplicationService;
import com.example.ivos.audit.mapper.AuditMapper;
import com.example.ivos.audit.pojo.vo.AuditVO;
import com.example.ivos.audit.service.AuditService;
import com.example.ivos.base.enums.ApplicationStatusEnum;
import com.example.ivos.user.mapper.UserMapper;
import com.example.ivos.user.pojo.vo.UserVO;
import com.example.ivos.vehicle.mapper.VehicleMapper;
import com.example.ivos.vehicle.pojo.entity.Vehicle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Transactional
@Slf4j
@Service
public class ApplicationServiceImpl implements ApplicationService{
    @Autowired
    ApplicationMapper applicationMapper;
    @Autowired
    AuditService auditService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public void save(ApplicationSaveParam applicationSaveParam) {
        log.debug("新增申请单的业务参数:{}",applicationSaveParam);
        Application application = new Application();
        BeanUtils.copyProperties(applicationSaveParam,application);
        application.setStatus(ApplicationStatusEnum.PENDING.getCode());
        application.setCreateTime(new Date());
        /* 遇到的问题:新增申请单对应的审批单数据时,审批单里没有申请单id
         * 原因: 执行insert方法对应的SQL时,并没有把刚刚生成的申请单id回填到application对象中
         * 解决办法:给此SQL上加 useGeneratedKeys="true" keyProperty="id" 属性
         * 效果: JDBC会自动回填申请单id到application对象的id属性中,再传给审批模块,审批就能拿到申请单id了 */
        applicationMapper.insert(application);

        /* 在生成申请后还要为此申请单生成对应的审批单数据 */
        auditService.insertAudit(application);
    }

    @Override
    public List<ApplicationVO> selectApplication(ApplicationQuery applicationQuery) {
        log.debug("查询申请单业务:applicationQuery={}",applicationQuery);
        List<ApplicationVO> list = applicationMapper.selectApplication(applicationQuery);
        //遍历每一个申请单,依次为每个遍历到的申请单添加审批人数据
        for(int i = 0;i < list.size();i++){
            ApplicationVO applicationVO = list.get(i);
            //处理当前的申请单VO,给它添加审批人数据
            assignAuditUserList(applicationVO);
        }
        return list;
    }

    @Override
    public void cancel(Long id) {
        log.debug("撤销申请单业务:id={}",id);
        Application application = new Application();
        application.setId(id);
        //撤销需要将申请单状态改为"撤销"
        application.setStatus(ApplicationStatusEnum.CANCEL.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);

        //还需要删除此申请单对应的所有审批单数据
        auditMapper.deleteByApplicationId(id);
    }

    /**
     * 为申请单VO补全审批人信息,此方法并不会产生额外的申请单VO!
     * List<Long> auditUserIdList; //[106,103]
     * String auditUsernameList; //"moly,tom"
     * @param applicationVO
     */
    private void assignAuditUserList(ApplicationVO applicationVO) {
        //1.准备空集合,分别用来保存当前传入申请单对应审批人的id与姓名
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //2.获取当前传入的申请单id,查询批此申请单的所有审批单VO
        List<AuditVO> auditVOList =
                auditService.selectAuditByApplicationId(applicationVO.getId());
        //3.依次遍历取出每一个审批单对象
        for(int i = 0; i < auditVOList.size(); i++){
            AuditVO auditVO = auditVOList.get(i);
            //4.获取当前遍历到的审批单VO中的审批人数据
            Long id = auditVO.getAuditUserId();
            auditUserIdList.add(id);
            //5.根据审批人id,查出审批人姓名
            UserVO userVO = userMapper.selectAudit(id);
            auditUsernameList.add(userVO.getUsername());
        }
        //6.准备一个拼接工具,帮我们把审批人姓名连成一个字符串
        StringJoiner stringJoiner = new StringJoiner(",");
        //7.依次将所有审批人姓名添加到拼接工具中
        for(String username : auditUsernameList){
            stringJoiner.add(username);
        }
        //8.为传入的申请单VO补全数据
        applicationVO.setAuditUserIdList(auditUserIdList);
        applicationVO.setAuditUsernameList(stringJoiner.toString());
    }
    @Override
    public void distribute(Long applicationId, Long vehicleId) {
        log.debug("分配车辆业务:applicationId={},vehicleId={}",applicationId,vehicleId);
        Application application = new Application();
        application.setId(applicationId);//设置要更新哪个申请单
        application.setVehicleId(vehicleId);//设置分配的是哪辆车
        application.setStatus(ApplicationStatusEnum.ALLOCATION.getCode());//设置申请单状态为60
        application.setUpdateTime(new Date());//设置更新时间
        applicationMapper.update(application);//数据层更新

        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);//设置要更新哪辆车
        vehicle.setStatus("2");//设置车辆状态为占用
        vehicle.setUpdateTime(new Date());//设置更新时间
        vehicleMapper.update(vehicle);//数据层更新
    }
    @Override
    public void back(Long applicationId, Long vehicleId) {
        log.debug("还车业务:applicationId={},vehicleId={}",applicationId,vehicleId);
        Application application = new Application();
        application.setId(applicationId);
        /* 车辆状态改为"空闲",申请单状态改为"工单结束",但申请单的车辆id要设置为null */
        application.setVehicleId(null);//设置要归还哪辆车
        //设置当前申请单的状态为"工单结束"
        application.setStatus(ApplicationStatusEnum.END.getCode());
        application.setUpdateTime(new Date());
        /* 需要重写一个将车辆id置为null值的新SQL*/
        applicationMapper.back(application);

        //还车需要把车辆状态修改为"空闲"
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}